package com.wqm.step.controller;

import java.util.Collection;
import java.util.Random;

import javax.ws.rs.core.MediaType;

import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wqm.step.pojo.Person;
import com.wqm.step.utils.JsonUtils;

@Controller
public class ShowPerson {

	@Value("${BASE_ADDRESS}")
	private String BASE_ADDRESS;

	@Value("${WEB_SERVICE}")
	private String WEB_SERVICE;

	// 查询所有的人, 这里要把person转换为json, 所以要引入json转换依赖
	@RequestMapping(value = "findAllPerson.action", produces = { "text/html;charset=UTF-8" })
	@ResponseBody
	public String findAllPerson() {
		Collection<? extends Person> persons = WebClient.create(WEB_SERVICE).path("/personService/person")
				.accept(MediaType.APPLICATION_JSON).getCollection(Person.class);
		return JsonUtils.objectToJson(persons);
	}

	// 根据id查询具体的人
	@RequestMapping(value = "findPerson.action", method = RequestMethod.GET, produces = {
			"text/html;charset=UTF-8" })
	@ResponseBody
	public String findPerson() {
		int pid = 1;
		Person person = WebClient.create(WEB_SERVICE + "/personService/person/" + pid).type(MediaType.APPLICATION_JSON)
				.get(Person.class);
		return JsonUtils.objectToJson(person);
	}

	// 添加人
	@RequestMapping(value = "savePerson.action")
	@ResponseBody
	public void addPerson() {
		Person person = new Person(15+new Random().nextInt(10), "王钦民", "四川", "15228119181");
		WebClient.create(WEB_SERVICE + "/personService/person").type(MediaType.APPLICATION_JSON).post(person);
	}
}
